﻿#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Core;

public class GameReferenceHierarchyEditor
{
    [InitializeOnLoadMethod]
    private static void Init()
    {
        EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyWindowItemOnGUI;
        EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
    }

    private static void OnHierarchyWindowItemOnGUI(int instanceID, Rect selectionRect)
    {
        var obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;

        if (obj == null)
            return;

        if(obj.GetComponent<GameReference>() != null)
        {
            var gr = obj.GetComponentsInParent<GameReference>();

            if (gr.Length == 0)
                return;

            var reference = gr[0];
            LoadReferenceAsset(reference);
        }
    }

    private static async void LoadReferenceAsset(GameReference reference)
    {
        if (string.IsNullOrEmpty(reference.assetPath))
            return;
        if (reference._isLoadFail)
            return;

        var item = await reference.LoadAsync<BaseReferenceItem>();
        if (item == null)
        {
            Debug.LogError($"预览失败:{reference.name}");
            reference._isLoadFail = true;
            return;
        }

        item.gameObject.hideFlags = HideFlags.HideAndDontSave;
    }
}

#endif